#include "qelib.h"
#include "qe_mmc.h"



QELOG_DOMAIN("mmc");



QE_LIST_INIT(mmc_list);



/* frequency bases */
/* divided by 10 to be nice to platforms without floating point */
static const int fbase[] = {
	10000,
	100000,
	1000000,
	10000000,
};

static const qe_u8 multipliers[] = {
	0,	/* reserved */
	10,
	12,
	13,
	15,
	20,
	25,
	30,
	35,
	40,
	45,
	50,
	55,
	60,
	70,
	80,
};



static qe_ret mmc_send_status(qe_mmc *mmc, qe_uint *status);



static qe_const_str mmc_mode_name(enum mmc_bus_mode mode)
{
	static const char *const names[] = {
	      [MMC_LEGACY]	= "MMC legacy",
	      [SD_LEGACY]	= "SD Legacy",
	      [MMC_HS]		= "MMC High Speed (26MHz)",
	      [SD_HS]		= "SD High Speed (50MHz)",
	      [UHS_SDR12]	= "UHS SDR12 (25MHz)",
	      [UHS_SDR25]	= "UHS SDR25 (50MHz)",
	      [UHS_SDR50]	= "UHS SDR50 (100MHz)",
	      [UHS_SDR104]	= "UHS SDR104 (208MHz)",
	      [UHS_DDR50]	= "UHS DDR50 (50MHz)",
	      [MMC_HS_52]	= "MMC High Speed (52MHz)",
	      [MMC_DDR_52]	= "MMC DDR52 (52MHz)",
	      [MMC_HS_200]	= "HS200 (200MHz)",
	      [MMC_HS_400]	= "HS400 (200MHz)",
	      [MMC_HS_400_ES]	= "HS400ES (200MHz)",
	};

	if (mode >= MMC_MODES_END)
		return "Unknown mode";
	else
		return names[mode];
}

static qe_uint mmc_mode2freq(qe_mmc *mmc, enum mmc_bus_mode mode)
{
	static const int freqs[] = {
	      [MMC_LEGACY]	= 25000000,
	      [SD_LEGACY]	= 25000000,
	      [MMC_HS]		= 26000000,
	      [SD_HS]		= 50000000,
	      [MMC_HS_52]	= 52000000,
	      [MMC_DDR_52]	= 52000000,
	      [UHS_SDR12]	= 25000000,
	      [UHS_SDR25]	= 50000000,
	      [UHS_SDR50]	= 100000000,
	      [UHS_DDR50]	= 50000000,
	      [UHS_SDR104]	= 208000000,
	      [MMC_HS_200]	= 200000000,
	      [MMC_HS_400]	= 200000000,
	      [MMC_HS_400_ES]	= 200000000,
	};

	if (mode == MMC_LEGACY)
		return mmc->legacy_speed;
	else if (mode >= MMC_MODES_END)
		return 0;
	else
		return freqs[mode];
}

static qe_ret mmc_send_cmd(qe_mmc *mmc, qe_mmc_cmd *cmd, qe_mmc_data *data)
{
    qe_info("send cmd:%d arg:%x", cmd->cmdidx, cmd->cmdarg);
    return mmc->ops->send_cmd(mmc, cmd, data);
}

static qe_ret mmc_set_ios(qe_mmc *mmc)
{
	int ret = qe_ok;

	if (mmc->ops->set_ios)
		ret = mmc->ops->set_ios(mmc);

	return ret;
}

static int mmc_set_bus_width(qe_mmc *mmc, qe_uint width)
{
	mmc->bus_width = width;

	return mmc_set_ios(mmc);
}

static qe_ret mmc_execute_tuning(qe_mmc *mmc, qe_uint opcode)
{
    if (mmc->ops->execute_tuning)
        return mmc->ops->execute_tuning(mmc, opcode);
    return qe_err_notsupport;
}

static qe_size mmc_read_blocks(qe_mmc *mmc, qe_size start, qe_size blkcnt, qe_ptr dst)
{
    qe_ret ret;
    qe_mmc_cmd cmd;
    qe_mmc_data data;

    if (blkcnt > 1) 
        cmd.cmdidx = MMC_CMD_READ_MULTIPLE_BLOCK;
    else
        cmd.cmdidx = MMC_CMD_READ_SINGLE_BLOCK;

    if (mmc->high_capacity)
        cmd.cmdarg = start;
    else
        cmd.cmdarg = start * mmc->read_bl_len;

    cmd.resp_type = MMC_RSP_R1;

	data.dest = dst;
	data.blocks = blkcnt;
	data.blocksize = mmc->read_bl_len;
	data.flags = MMC_DATA_READ;

    ret = mmc_send_cmd(mmc, &cmd, &data);
    if (ret != qe_ok) {
        qe_error("%s send cmd error:%d", mmc->dev.name, ret);
        return -ret;
    }

    if (blkcnt > 1) {
		cmd.cmdidx = MMC_CMD_STOP_TRANSMISSION;
		cmd.cmdarg = 0;
		cmd.resp_type = MMC_RSP_R1b;
        ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
        if (ret != qe_ok) {
            qe_error("%s stop transmit error:%d", mmc->dev.name, ret);
            return -ret;
        }
    }

    return blkcnt;
}


qe_bool mmc_poll_for_busy(qe_mmc *mmc, int timeout_ms)
{
	qe_ret ret;
	unsigned int status;

	while (1) {
		ret = mmc_send_status(mmc, &status);
		if (ret != qe_ok)
			return ret;

		if ((status & MMC_STATUS_RDY_FOR_DATA) &&
		    (status & MMC_STATUS_CURR_STATE) !=
		     MMC_STATE_PRG)
			break;

		if (status & MMC_STATUS_MASK) {
			qe_error("status error: 0x%08x", status);
			return qe_err_common;
		}

		if (timeout_ms-- <= 0)
			break;

		qe_usleep(1000);
	}

	if (timeout_ms <= 0) {
		qe_error("timeout waiting card ready");
		return qe_err_timeout;
	}

	return qe_ok;
}

static qe_size mmc_write_blocks(qe_mmc *mmc, qe_size start, qe_size blkcnt, qe_const_ptr src)
{
    qe_mmc_cmd cmd;
    qe_mmc_data data;
    int timeout_ms = 1000;

	if ((start + blkcnt) > mmc->lba) {
		qe_error("block number %d exceeds max %d",
		       start + blkcnt, mmc->lba);
		return 0;
	}

	if (blkcnt == 0)
		return 0;
	else if (blkcnt == 1)
		cmd.cmdidx = MMC_CMD_WRITE_SINGLE_BLOCK;
	else
		cmd.cmdidx = MMC_CMD_WRITE_MULTIPLE_BLOCK;

	if (mmc->high_capacity)
		cmd.cmdarg = start;
	else
		cmd.cmdarg = start * mmc->write_bl_len;

	cmd.resp_type = MMC_RSP_R1;

	data.src = src;
	data.blocks = blkcnt;
	data.blocksize = mmc->write_bl_len;
	data.flags = MMC_DATA_WRITE;

	if (mmc_send_cmd(mmc, &cmd, &data)) {
		qe_printf("mmc write failed");
		return 0;
	}

	/* SPI multiblock writes terminate using a special
	 * token, not a STOP_TRANSMISSION request.
	 */
	if (!mmc_host_is_spi(mmc) && blkcnt > 1) {
		cmd.cmdidx = MMC_CMD_STOP_TRANSMISSION;
		cmd.cmdarg = 0;
		cmd.resp_type = MMC_RSP_R1b;
		if (mmc_send_cmd(mmc, &cmd, QE_NULL)) {
			qe_error("mmc fail to send stop cmd");
			return 0;
		}
	}

	/* Waiting for the ready status */
	if (mmc_poll_for_busy(mmc, timeout_ms))
		return 0;

	return blkcnt;
}

static qe_ret mmc_go_idle(qe_mmc *mmc)
{
    qe_ret ret;
	qe_mmc_cmd cmd;

	qe_usleep(1000);

	cmd.cmdidx = MMC_CMD_GO_IDLE_STATE;
	cmd.cmdarg = 0;
	cmd.resp_type = MMC_RSP_NONE;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
	if (ret != qe_ok) {
        qe_error("send cmd %d err:%d", cmd.cmdidx, ret);
        return ret;
    }

	qe_usleep(2000);

	return qe_ok;
}

static qe_bool mmc_getcd(qe_mmc *mmc)
{
    qe_bool cd;

    if (mmc->ops->getcd) {
        qe_debug("call ops->getcd");
        cd = mmc->ops->getcd(mmc);
    } else {
        qe_debug("ops no getcd, fix cd true");
        cd = qe_true;
    }
    return cd;
}

static qe_ret mmc_set_clock(qe_mmc *mmc, qe_uint clock, qe_bool disable)
{
	if (!disable) {
		if (clock > mmc->cfg->f_max) {
			clock = mmc->cfg->f_max;
            qe_debug("using cfg:%p fmax %d", mmc->cfg, clock);
        }

		if (clock < mmc->cfg->f_min) {
			clock = mmc->cfg->f_min;
            qe_debug("using cfg:%p fmin %d", mmc->cfg, clock);
        }
	}

	mmc->clock = clock;
	mmc->clk_disable = disable;

	qe_debug("clock is %s %dHz", disable ? "disabled" : "enabled", clock);

	return mmc_set_ios(mmc);
}

static qe_ret mmc_power_off(qe_mmc *mmc)
{
	mmc_set_clock(mmc, 0, MMC_CLK_DISABLE);

	return qe_ok;
}

static qe_ret mmc_power_on(qe_mmc *mmc)
{
	return qe_ok;
}

static qe_ret mmc_host_power_cycle(qe_mmc *mmc)
{
	qe_ret ret = qe_ok;

	if (mmc->ops->host_power_cycle)
		ret = mmc->ops->host_power_cycle(mmc);

	return ret;
}

static qe_ret mmc_power_cycle(qe_mmc *mmc)
{
	qe_ret ret;

	ret = mmc_power_off(mmc);
	if (ret != qe_ok)
		return ret;

	ret = mmc_host_power_cycle(mmc);
	if (ret != qe_ok)
		return ret;

	/*
	 * SD spec recommends at least 1ms of delay. Let's wait for 2ms
	 * to be on the safer side.
	 */
	qe_usleep(2000);
	return mmc_power_on(mmc);
}

static qe_ret mmc_set_signal_voltage(qe_mmc *mmc, qe_uint signal_voltage)
{
	qe_ret ret;

	if (mmc->signal_voltage == signal_voltage)
		return qe_ok;

	mmc->signal_voltage = signal_voltage;
	ret = mmc_set_ios(mmc);
	if (ret != qe_ok)
		qe_error("set voltage error:%d", ret);

	return ret;
}

static inline qe_bool mmc_is_mode_ddr(enum mmc_bus_mode mode)
{
	if (mode == MMC_DDR_52)
		return qe_true;
	else if (mode == UHS_DDR50)
		return qe_true;
	else if (mode == MMC_HS_400)
		return qe_true;
	else if (mode == MMC_HS_400_ES)
		return qe_true;
	else
		return qe_false;
}

static qe_ret mmc_select_mode(qe_mmc *mmc, enum mmc_bus_mode mode)
{
	mmc->selected_mode = mode;
	mmc->tran_speed = mmc_mode2freq(mmc, mode);
	mmc->ddr_mode = mmc_is_mode_ddr(mode);
	qe_debug("selecting mode %s (freq : %d MHz)", mmc_mode_name(mode),
		 mmc->tran_speed / 1000000);
	return 0;
}

static qe_ret mmc_send_ext_csd(qe_mmc *mmc, qe_u8 *ext_csd)
{
    qe_ret ret;
	qe_mmc_cmd cmd;
	qe_mmc_data data;

    if (MMC_IS_SD(mmc) || (mmc->version < MMC_VERSION_4)) {
        return qe_ok;
    }

	/* Get the Card Status Register */
	cmd.cmdidx = MMC_CMD_SEND_EXT_CSD;
	cmd.resp_type = MMC_RSP_R1;
	cmd.cmdarg = 0;

	data.dest = (char *)ext_csd;
	data.blocks = 1;
	data.blocksize = MMC_MAX_BLOCK_LEN;
	data.flags = MMC_DATA_READ;
    qe_debug("ext_csd %p", ext_csd);
	ret = mmc_send_cmd(mmc, &cmd, &data);

	return ret;
}

static qe_ret mmc_wait_dat0(qe_mmc *mmc, int state, int timeout_us)
{
	return qe_err_notsupport;
}

static qe_ret mmc_switch_voltage(qe_mmc *mmc, qe_int signal_voltage)
{
    qe_ret ret = qe_ok;
	qe_mmc_cmd cmd;
	
	/*
	 * Send CMD11 only if the request is to switch the card to
	 * 1.8V signalling.
	 */
	if (signal_voltage == MMC_SIGNAL_VOLTAGE_330)
		return mmc_set_signal_voltage(mmc, signal_voltage);

	cmd.cmdidx = SD_CMD_SWITCH_UHS18V;
	cmd.cmdarg = 0;
	cmd.resp_type = MMC_RSP_R1;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
	if (ret != qe_ok)
		return ret;

	if (!mmc_host_is_spi(mmc) && (cmd.response[0] & MMC_STATUS_ERROR))
		return qe_err_common;

	/*
	 * The card should drive cmd and dat[0:3] low immediately
	 * after the response of cmd11, but wait 100 us to be sure
	 */
	ret = mmc_wait_dat0(mmc, 0, 100);
	if (ret == qe_err_notsupport)
		qe_usleep(100);
	else if (ret != qe_ok)
		return qe_err_timeout;

	/*
	 * During a signal voltage level switch, the clock must be gated
	 * for 5 ms according to the SD spec
	 */
	mmc_set_clock(mmc, mmc->clock, MMC_CLK_DISABLE);

	ret = mmc_set_signal_voltage(mmc, signal_voltage);
	if (ret != qe_ok)
		return ret;

	/* Keep clock gated for at least 10 ms, though spec only says 5 ms */
	qe_msleep(10);
	mmc_set_clock(mmc, mmc->clock, MMC_CLK_ENABLE);

	/*
	 * Failure to switch is indicated by the card holding
	 * dat[0:3] low. Wait for at least 1 ms according to spec
	 */
	ret = mmc_wait_dat0(mmc, 1, 1000);
	if (ret == qe_err_notsupport)
		qe_usleep(1000);
	else if (ret != qe_ok)
		return qe_err_timeout;

	return qe_ok;
}

static qe_ret mmc_send_op_cond_iter(qe_mmc *mmc, qe_int use_arg)
{
	qe_ret ret;
    qe_mmc_cmd cmd;

    qe_debug("mmc_send_op_cond_iter in");

	cmd.cmdidx = MMC_CMD_SEND_OP_COND;
	cmd.resp_type = MMC_RSP_R3;
	cmd.cmdarg = 0;
	if (use_arg && !mmc_host_is_spi(mmc))
		cmd.cmdarg = MMC_OCR_HCS |
			(mmc->cfg->voltages &
			(mmc->ocr & MMC_OCR_VOLTAGE_MASK)) |
			(mmc->ocr & MMC_OCR_ACCESS_MODE);

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
	if (ret != qe_ok)
		return ret;
	mmc->ocr = cmd.response[0];
    qe_debug("OCR:%x", mmc->ocr);
	return qe_ok;
}

static qe_ret mmc_send_op_cond(qe_mmc *mmc)
{
	qe_ret ret, i;

	/* Some cards seem to need this */
	mmc_go_idle(mmc);
    qe_info("mmc go idle");

 	/* Asking to the card its capabilities */
	for (i = 0; i < 2; i++) {
		ret = mmc_send_op_cond_iter(mmc, i != 0);
		if (ret != qe_ok)
			return ret;

		/* exit if not busy (flag seems to be inverted) */
		if (mmc->ocr & MMC_OCR_BUSY)
			break;
	}
	mmc->op_cond_pending = 1;
	return qe_ok;
}

static qe_ret sd_send_op_cond(qe_mmc *mmc, qe_bool uhs_en)
{
    qe_ret ret;
	qe_uint timeout = 1000;
	qe_mmc_cmd cmd;

	while (1) {
		cmd.cmdidx = MMC_CMD_APP_CMD;
		cmd.resp_type = MMC_RSP_R1;
		cmd.cmdarg = 0;

		ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
		if (ret != qe_ok)
			return ret;

		cmd.cmdidx = SD_CMD_APP_SEND_OP_COND;
		cmd.resp_type = MMC_RSP_R3;

		/*
		 * Most cards do not answer if some reserved bits
		 * in the ocr are set. However, Some controller
		 * can set bit 7 (reserved for low voltages), but
		 * how to manage low voltages SD card is not yet
		 * specified.
		 */
		cmd.cmdarg = mmc_host_is_spi(mmc) ? 0 :
			(mmc->cfg->voltages & 0xff8000);

		if (mmc->version == SD_VERSION_2)
			cmd.cmdarg |= MMC_OCR_HCS;

		if (uhs_en)
			cmd.cmdarg |= MMC_OCR_S18R;

		ret = mmc_send_cmd(mmc, &cmd, QE_NULL);

		if (ret != qe_ok)
			return ret;

		if (cmd.response[0] & MMC_OCR_BUSY)
			break;

		if (timeout-- <= 0)
			return qe_err_timeout;

		qe_usleep(1000);
	}

	if (mmc->version != SD_VERSION_2)
		mmc->version = SD_VERSION_1_0;

	if (mmc_host_is_spi(mmc)) { /* read OCR for spi */
		cmd.cmdidx = MMC_CMD_SPI_READ_OCR;
		cmd.resp_type = MMC_RSP_R3;
		cmd.cmdarg = 0;

		ret = mmc_send_cmd(mmc, &cmd, QE_NULL);

		if (ret != qe_ok)
			return ret;
	}

	mmc->ocr = cmd.response[0];

	if (uhs_en && !(mmc_host_is_spi(mmc)) && (cmd.response[0] & 0x41000000)
	    == 0x41000000) {
		ret = mmc_switch_voltage(mmc, MMC_SIGNAL_VOLTAGE_180);
		if (ret != qe_ok)
			return ret;
	}

	mmc->high_capacity = ((mmc->ocr & MMC_OCR_HCS) == MMC_OCR_HCS);
	mmc->rca = 0;

	return 0;
}

static qe_ret mmc_send_if_cond(qe_mmc *mmc)
{
    qe_ret ret;
	qe_mmc_cmd cmd;

    qe_debug("mmc_send_if_cond in");

	cmd.cmdidx = SD_CMD_SEND_IF_COND;
	/* We set the bit if the host supports voltages between 2.7 and 3.6 V */
	cmd.cmdarg = ((mmc->cfg->voltages & 0xff8000) != 0) << 8 | 0xaa;
	cmd.resp_type = MMC_RSP_R7;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);

	if (ret != qe_ok) {
        qe_error("send cmd:%d error:%d", cmd.cmdidx, ret);
		return ret;
    }

	if ((cmd.response[0] & 0xff) != 0xaa)
		return qe_err_notsupport;
	else
		mmc->version = SD_VERSION_2;

	return 0;
}

/*
 * put the host in the initial state:
 * - turn on Vdd (card power supply)
 * - configure the bus width and clock to minimal values
 */
static void mmc_set_initial_state(qe_mmc *mmc)
{
	qe_ret ret;

    qe_debug("mmc_set_initial_state in");

	/* First try to set 3.3V. If it fails set to 1.8V */
	ret = mmc_set_signal_voltage(mmc, MMC_SIGNAL_VOLTAGE_330);
	if (ret != qe_ok)
		ret = mmc_set_signal_voltage(mmc, MMC_SIGNAL_VOLTAGE_180);
	if (ret != qe_ok)
		qe_warning("failed to set signal voltage");

	mmc_select_mode(mmc, MMC_LEGACY);
	mmc_set_bus_width(mmc, 1);
	mmc_set_clock(mmc, 0, MMC_CLK_ENABLE);
}

static qe_ret mmc_get_op_cond(qe_mmc *mmc)
{
    qe_ret ret;
    qe_bool uhs_en = mmc_supports_uhs(mmc->cfg->host_caps);

    qe_debug("mmc_get_op_cond in");

	if (mmc->has_init)
		return qe_ok;

    ret = mmc_power_cycle(mmc);
    if (ret != qe_ok) {
		/*
		 * if power cycling is not supported, we should not try
		 * to use the UHS modes, because we wouldn't be able to
		 * recover from an error during the UHS initialization.
		 */
        uhs_en = qe_false;
        mmc->host_caps &= ~MMC_UHS_CAPS;
        ret = mmc_power_on(mmc);
    }

    if (ret != qe_ok)
        return ret;
    
retry:
    mmc_set_initial_state(mmc);

    /* Reset the card */
    ret = mmc_go_idle(mmc);
    if (ret != qe_ok) {
    	return ret;
    }
    qe_debug("reset card success");

	/* Test for SD version 2 */
	mmc_send_if_cond(mmc);

    ret = sd_send_op_cond(mmc, uhs_en);
    if (ret != qe_ok && uhs_en) {
        uhs_en = qe_false;
        mmc_power_cycle(mmc);
        goto retry;
    }

    ret = qe_err_timeout;
    /* If the command timed out, we check for an MMC card */
    if (ret == qe_err_timeout) {
        qe_debug("sd op cond timeout, check mmc");
        ret = mmc_send_op_cond(mmc);
        if (ret != qe_ok) {
            qe_error("card not respond to voltage select");
            return qe_err_common;
        }
    }

    qe_info("check MMC card success");

    return ret;
}

static qe_ret mmc_complete_op_cond(qe_mmc *mmc)
{
    qe_ret ret;
    qe_time_t start;
	qe_uint timeout = 1000;
	
    qe_mmc_cmd cmd;

	mmc->op_cond_pending = 0;
	if (!(mmc->ocr & MMC_OCR_BUSY)) {
		/* Some cards seem to need this */
		mmc_go_idle(mmc);

		start = qe_time_ms();
		while (1) {
			ret = mmc_send_op_cond_iter(mmc, 1);
			if (ret != qe_ok)
				return ret;
			if (mmc->ocr & MMC_OCR_BUSY)
				break;
			if ((qe_time_ms() - start) > timeout)
				return qe_err_timeout;
			qe_usleep(100);
		}
	}

	if (mmc_host_is_spi(mmc)) { /* read OCR for spi */
		cmd.cmdidx = MMC_CMD_SPI_READ_OCR;
		cmd.resp_type = MMC_RSP_R3;
		cmd.cmdarg = 0;

		ret = mmc_send_cmd(mmc, &cmd, QE_NULL);

		if (ret != qe_ok)
			return ret;

		mmc->ocr = cmd.response[0];
	}

	mmc->version = MMC_VERSION_UNKNOWN;

	mmc->high_capacity = ((mmc->ocr & MMC_OCR_HCS) == MMC_OCR_HCS);
	mmc->rca = 1;

	return 0;
}

static qe_ret mmc_start_init(qe_mmc *mmc)
{
    qe_ret ret;
    qe_bool no_card;

	/*
	 * all hosts are capable of 1 bit bus-width and able to use the legacy
	 * timings.
	 */
    mmc->host_caps = mmc->cfg->host_caps | 
                     MMC_CAP(SD_LEGACY) |
                     MMC_CAP(MMC_LEGACY) |
                     MMC_MODE_1BIT;
    
    no_card = !mmc_getcd(mmc);

    if (no_card) {
        mmc->has_init = 0;
        qe_error("no card present");
        return qe_err_notfind;
    }

    ret = mmc_get_op_cond(mmc);
    if (ret == qe_ok) {
        mmc->init_in_progress = 1;
    }

    return ret;
}

static qe_ret mmc_send_status(qe_mmc *mmc, qe_uint *status)
{
	int retries = 5;
	qe_ret ret;
	qe_mmc_cmd cmd;


	cmd.cmdidx = MMC_CMD_SEND_STATUS;
	cmd.resp_type = MMC_RSP_R1;
	if (!mmc_host_is_spi(mmc))
		cmd.cmdarg = mmc->rca << 16;

	while (retries--) {
		ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
		if (ret == qe_ok) {
			*status = cmd.response[0];
			return 0;
		}
	}
	return qe_err_common;
}


static qe_ret mmc_switch(qe_mmc *mmc, qe_u8 set, qe_u8 index, qe_u8 value, qe_bool send_status)
{
    int retries = 3;
    qe_ret ret;
    qe_uint status;
    qe_time_t start;
    qe_mmc_cmd cmd;
	int timeout_ms = 500;
	qe_bool is_part_switch = (set == MMC_EXT_CSD_CMD_SET_NORMAL) &&
			      (index == MMC_EXT_CSD_PART_CONF);

	if (mmc->gen_cmd6_time)
		timeout_ms = mmc->gen_cmd6_time * 10;

	if (is_part_switch  && mmc->part_switch_time)
		timeout_ms = mmc->part_switch_time * 10;

	cmd.cmdidx = MMC_CMD_SWITCH;
	cmd.resp_type = MMC_RSP_R1b;
	cmd.cmdarg = (MMC_SWITCH_MODE_WRITE_BYTE << 24) |
				 (index << 16) |
				 (value << 8);

	do {
		ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
	} while (ret && retries-- > 0);

	if (ret)
		return ret;

	start = qe_time_ms();

	/* poll dat0 for rdy/buys status */
	ret = mmc_wait_dat0(mmc, 1, timeout_ms * 1000);
	if (ret && ret != qe_err_notsupport)
		return ret;

	/*
	 * In cases when not allowed to poll by using CMD13 or because we aren't
	 * capable of polling by using mmc_wait_dat0, then rely on waiting the
	 * stated timeout to be sufficient.
	 */
	if (ret == qe_err_notsupport && !send_status)
		qe_msleep(timeout_ms);

	/* Finally wait until the card is ready or indicates a failure
	 * to switch. It doesn't hurt to use CMD13 here even if send_status
	 * is false, because by now (after 'timeout_ms' ms) the bus should be
	 * reliable.
	 */
	do {
		ret = mmc_send_status(mmc, &status);

		if (!ret && (status & MMC_STATUS_SWITCH_ERROR)) {
			qe_error("switch failed %d/%d/0x%x", set, index, value);
			return qe_err_common;
		}
		if (!ret && (status & MMC_STATUS_RDY_FOR_DATA))
			return 0;
		qe_usleep(100);
	} while ((qe_time_ms() - start) < timeout_ms);

	return qe_err_timeout;
}

static qe_ret mmc_startup_v4(qe_mmc *mmc)
{
    int i;
    qe_u8 qe_aligned(32) ext_csd[MMC_MAX_BLOCK_LEN];
	qe_ret ret;
	qe_u64 capacity;
	qe_bool has_parts = qe_false;
	qe_bool part_completed;
	static const qe_u32 mmc_versions[] = {
		MMC_VERSION_4,
		MMC_VERSION_4_1,
		MMC_VERSION_4_2,
		MMC_VERSION_4_3,
		MMC_VERSION_4_4,
		MMC_VERSION_4_41,
		MMC_VERSION_4_5,
		MMC_VERSION_5_0,
		MMC_VERSION_5_1
	};

	if (MMC_IS_SD(mmc) || (mmc->version < MMC_VERSION_4))
		return qe_ok;

	/* check ext_csd version and capacity */
	qe_memset(ext_csd, 0, sizeof(ext_csd));
	ret = mmc_send_ext_csd(mmc, ext_csd);
	if (ret != qe_ok)
		goto error;

	/* store the ext csd for future reference */
	if (!mmc->ext_csd)
		mmc->ext_csd = qe_malloc(MMC_MAX_BLOCK_LEN);
	if (!mmc->ext_csd)
		return qe_err_mem;
	qe_memcpy(mmc->ext_csd, ext_csd, MMC_MAX_BLOCK_LEN);

	if (ext_csd[MMC_EXT_CSD_REV] >= qe_array_size(mmc_versions))
		return qe_err_param;

	qe_debug("escd:");
	qe_hexdump_debug(mmc->ext_csd, MMC_MAX_BLOCK_LEN);
	qe_debug("card type:%d", ext_csd[MMC_EXT_CSD_CARD_TYPE]);

	mmc->version = mmc_versions[ext_csd[MMC_EXT_CSD_REV]];
	qe_debug("mmc version:%d %x", ext_csd[MMC_EXT_CSD_REV], mmc->version);
	if (mmc->version >= MMC_VERSION_4_2) {
		qe_debug("mmc version >= V4.2");
		/*
		 * According to the JEDEC Standard, the value of
		 * ext_csd's capacity is valid if the value is more
		 * than 2GB
		 */
		capacity = ext_csd[MMC_EXT_CSD_SEC_CNT] << 0
				| ext_csd[MMC_EXT_CSD_SEC_CNT + 1] << 8
				| ext_csd[MMC_EXT_CSD_SEC_CNT + 2] << 16
				| ext_csd[MMC_EXT_CSD_SEC_CNT + 3] << 24;
		capacity *= MMC_MAX_BLOCK_LEN;
		if ((capacity >> 20) > 2 * 1024)
			mmc->capacity_user = capacity;
		qe_debug("capacity:%llu", mmc->capacity_user);
	}

	if (mmc->version >= MMC_VERSION_4_5)
		mmc->gen_cmd6_time = ext_csd[MMC_EXT_CSD_GENERIC_CMD6_TIME];

	/* The partition data may be non-zero but it is only
	 * effective if PARTITION_SETTING_COMPLETED is set in
	 * EXT_CSD, so ignore any data if this bit is not set,
	 * except for enabling the high-capacity group size
	 * definition (see below).
	 */
	part_completed = !!(ext_csd[MMC_EXT_CSD_PARTITION_SETTING] &
			    MMC_EXT_CSD_PARTITION_SETTING_COMPLETED);
	qe_debug("part completed:%d", part_completed);
	mmc->part_switch_time = ext_csd[MMC_EXT_CSD_PART_SWITCH_TIME];
	/* Some eMMC set the value too low so set a minimum */
	if (mmc->part_switch_time < MMC_MIN_PART_SWITCH_TIME && mmc->part_switch_time)
		mmc->part_switch_time = MMC_MIN_PART_SWITCH_TIME;

	/* store the partition info of emmc */
	mmc->part_support = ext_csd[MMC_EXT_CSD_PARTITIONING_SUPPORT];
	if ((ext_csd[MMC_EXT_CSD_PARTITIONING_SUPPORT] & MMC_PART_SUPPORT) ||
	    ext_csd[MMC_EXT_CSD_BOOT_MULT])
		mmc->part_config = ext_csd[MMC_EXT_CSD_PART_CONF];
	if (part_completed &&
	    (ext_csd[MMC_EXT_CSD_PARTITIONING_SUPPORT] & MMC_ENHNCD_SUPPORT))
		mmc->part_attr = ext_csd[MMC_EXT_CSD_PARTITIONS_ATTRIBUTE];

	mmc->capacity_boot = ext_csd[MMC_EXT_CSD_BOOT_MULT] << 17;

	mmc->capacity_rpmb = ext_csd[MMC_EXT_CSD_RPMB_MULT] << 17;

	for (i = 0; i < 4; i++) {
		int idx = MMC_EXT_CSD_GP_SIZE_MULT + i * 3;
		qe_uint mult = (ext_csd[idx + 2] << 16) +
			(ext_csd[idx + 1] << 8) + ext_csd[idx];
		if (mult)
			has_parts = qe_true;
		if (!part_completed)
			continue;
		mmc->capacity_gp[i] = mult;
		mmc->capacity_gp[i] *=
			ext_csd[MMC_EXT_CSD_HC_ERASE_GRP_SIZE];
		mmc->capacity_gp[i] *= ext_csd[MMC_EXT_CSD_HC_WP_GRP_SIZE];
		mmc->capacity_gp[i] <<= 19;
	}

	if (part_completed) {
		mmc->enh_user_size =
			(ext_csd[MMC_EXT_CSD_ENH_SIZE_MULT + 2] << 16) +
			(ext_csd[MMC_EXT_CSD_ENH_SIZE_MULT + 1] << 8) +
			ext_csd[MMC_EXT_CSD_ENH_SIZE_MULT];
		mmc->enh_user_size *= ext_csd[MMC_EXT_CSD_HC_ERASE_GRP_SIZE];
		mmc->enh_user_size *= ext_csd[MMC_EXT_CSD_HC_WP_GRP_SIZE];
		mmc->enh_user_size <<= 19;
		mmc->enh_user_start =
			(ext_csd[MMC_EXT_CSD_ENH_START_ADDR + 3] << 24) +
			(ext_csd[MMC_EXT_CSD_ENH_START_ADDR + 2] << 16) +
			(ext_csd[MMC_EXT_CSD_ENH_START_ADDR + 1] << 8) +
			ext_csd[MMC_EXT_CSD_ENH_START_ADDR];
		if (mmc->high_capacity)
			mmc->enh_user_start <<= 9;
	}

	/*
	 * Host needs to enable ERASE_GRP_DEF bit if device is
	 * partitioned. This bit will be lost every time after a reset
	 * or power off. This will affect erase size.
	 */
	if (part_completed)
		has_parts = qe_true;
	if ((ext_csd[MMC_EXT_CSD_PARTITIONING_SUPPORT] & MMC_PART_SUPPORT) &&
	    (ext_csd[MMC_EXT_CSD_PARTITIONS_ATTRIBUTE] & MMC_PART_ENH_ATTRIB))
		has_parts = qe_true;
	if (has_parts) {
		ret = mmc_switch(mmc, MMC_EXT_CSD_CMD_SET_NORMAL,
				 MMC_EXT_CSD_ERASE_GROUP_DEF, 1, qe_true);

		if (ret != qe_ok)
			goto error;

		ext_csd[MMC_EXT_CSD_ERASE_GROUP_DEF] = 1;
	}

	if (ext_csd[MMC_EXT_CSD_ERASE_GROUP_DEF] & 0x01) {

		/* Read out group size from ext_csd */
		mmc->erase_grp_size =
			ext_csd[MMC_EXT_CSD_HC_ERASE_GRP_SIZE] * 1024;

		/*
		 * if high capacity and partition setting completed
		 * SEC_COUNT is valid even if it is smaller than 2 GiB
		 * JEDEC Standard JESD84-B45, 6.2.4
		 */
		if (mmc->high_capacity && part_completed) {
			capacity = (ext_csd[MMC_EXT_CSD_SEC_CNT]) |
				(ext_csd[MMC_EXT_CSD_SEC_CNT + 1] << 8) |
				(ext_csd[MMC_EXT_CSD_SEC_CNT + 2] << 16) |
				(ext_csd[MMC_EXT_CSD_SEC_CNT + 3] << 24);
			capacity *= MMC_MAX_BLOCK_LEN;
			mmc->capacity_user = capacity;
		}
	}

	else {
		/* Calculate the group size from the csd value. */
		int erase_gsz, erase_gmul;

		erase_gsz = (mmc->csd[2] & 0x00007c00) >> 10;
		erase_gmul = (mmc->csd[2] & 0x000003e0) >> 5;
		mmc->erase_grp_size = (erase_gsz + 1)
			* (erase_gmul + 1);
	}

	mmc->hc_wp_grp_size = 1024
		* ext_csd[MMC_EXT_CSD_HC_ERASE_GRP_SIZE]
		* ext_csd[MMC_EXT_CSD_HC_WP_GRP_SIZE];

	mmc->wr_rel_set = ext_csd[MMC_EXT_CSD_WR_REL_SET];

	return qe_ok;
error:
	if (mmc->ext_csd) {
		qe_free(mmc->ext_csd);
		mmc->ext_csd = QE_NULL;
	}
	return ret;
}

static int sd_switch(qe_mmc *mmc, int mode, int group, qe_u8 value, qe_u8 *resp)
{
	qe_mmc_cmd cmd;
	qe_mmc_data data;

	/* Switch the frequency */
	cmd.cmdidx = SD_CMD_SWITCH_FUNC;
	cmd.resp_type = MMC_RSP_R1;
	cmd.cmdarg = (mode << 31) | 0xffffff;
	cmd.cmdarg &= ~(0xf << (group * 4));
	cmd.cmdarg |= value << (group * 4);

	data.dest = (char *)resp;
	data.blocksize = 64;
	data.blocks = 1;
	data.flags = MMC_DATA_READ;

	return mmc_send_cmd(mmc, &cmd, &data);
}

static qe_ret sd_get_capabilities(qe_mmc *mmc)
{
	qe_ret ret;
	qe_mmc_cmd cmd;
	qe_u32 qe_aligned(32) scr[2];
	qe_u32 qe_aligned(32) switch_status[16];
	qe_mmc_data data;
	int timeout;
	qe_u32 sd3_bus_mode;

	mmc->card_caps = MMC_MODE_1BIT | MMC_CAP(SD_LEGACY);

	if (mmc_host_is_spi(mmc))
		return 0;

	/* Read the SCR to find out if this card supports higher speeds */
	cmd.cmdidx = MMC_CMD_APP_CMD;
	cmd.resp_type = MMC_RSP_R1;
	cmd.cmdarg = mmc->rca << 16;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
	if (ret != qe_ok)
		return ret;

	cmd.cmdidx = SD_CMD_APP_SEND_SCR;
	cmd.resp_type = MMC_RSP_R1;
	cmd.cmdarg = 0;

	timeout = 3;

retry_scr:
	data.dest = (char *)scr;
	data.blocksize = 8;
	data.blocks = 1;
	data.flags = MMC_DATA_READ;

	ret = mmc_send_cmd(mmc, &cmd, &data);
	if (ret != qe_ok) {
		if (timeout--)
			goto retry_scr;

		return ret;
	}

	mmc->scr[0] = qe_swab32(scr[0]);
	mmc->scr[1] = qe_swab32(scr[1]);

	switch ((mmc->scr[0] >> 24) & 0xf) {
	case 0:
		mmc->version = SD_VERSION_1_0;
		break;
	case 1:
		mmc->version = SD_VERSION_1_10;
		break;
	case 2:
		mmc->version = SD_VERSION_2;
		if ((mmc->scr[0] >> 15) & 0x1)
			mmc->version = SD_VERSION_3;
		break;
	default:
		mmc->version = SD_VERSION_1_0;
		break;
	}

	if (mmc->scr[0] & SD_DATA_4BIT)
		mmc->card_caps |= MMC_MODE_4BIT;

	/* Version 1.0 doesn't support switching */
	if (mmc->version == SD_VERSION_1_0)
		return 0;

	timeout = 4;
	while (timeout--) {
		ret = sd_switch(mmc, SD_SWITCH_CHECK, 0, 1, (qe_u8 *)switch_status);
		if (ret != qe_ok)
			return ret;

		/* The high-speed function is busy.  Try again */
		if (!(qe_swab32(switch_status[7]) & SD_HIGHSPEED_BUSY))
			break;
	}

	/* If high-speed isn't supported, we return */
	if (qe_swab32(switch_status[3]) & SD_HIGHSPEED_SUPPORTED)
		mmc->card_caps |= MMC_CAP(SD_HS);

	/* Version before 3.0 don't support UHS modes */
	if (mmc->version < SD_VERSION_3)
		return 0;

	sd3_bus_mode = qe_swab32(switch_status[3]) >> 16 & 0x1f;
	if (sd3_bus_mode & SD_MODE_UHS_SDR104)
		mmc->card_caps |= MMC_CAP(UHS_SDR104);
	if (sd3_bus_mode & SD_MODE_UHS_SDR50)
		mmc->card_caps |= MMC_CAP(UHS_SDR50);
	if (sd3_bus_mode & SD_MODE_UHS_SDR25)
		mmc->card_caps |= MMC_CAP(UHS_SDR25);
	if (sd3_bus_mode & SD_MODE_UHS_SDR12)
		mmc->card_caps |= MMC_CAP(UHS_SDR12);
	if (sd3_bus_mode & SD_MODE_UHS_DDR50)
		mmc->card_caps |= MMC_CAP(UHS_DDR50);

	return qe_ok;
}

static qe_ret mmc_set_capacity(qe_mmc *mmc, int part_num)
{
	switch (part_num) {
	case 0:
		mmc->capacity = mmc->capacity_user;
		break;
	case 1:
	case 2:
		mmc->capacity = mmc->capacity_boot;
		break;
	case 3:
		mmc->capacity = mmc->capacity_rpmb;
		break;
	case 4:
	case 5:
	case 6:
	case 7:
		mmc->capacity = mmc->capacity_gp[part_num - 4];
		break;
	default:
		return -1;
	}

	mmc->lba = mmc->capacity / mmc->read_bl_len;

	return 0;
}

void mmc_dump_capabilities(const char *text, qe_uint caps)
{
	int width;
	enum mmc_bus_mode mode;

	qe_debug("%s:", text);
	if (caps & MMC_MODE_8BIT)
		width = 8;
	if (caps & MMC_MODE_4BIT)
		width = 4;
	if (caps & MMC_MODE_1BIT)
		width = 1;
	qe_debug("widths:%d", width);
	for (mode = MMC_LEGACY; mode < MMC_MODES_END; mode++)
		if (MMC_CAP(mode) & caps)
			qe_debug("mode:%s, ", mmc_mode_name(mode));
}

struct mode_width_tuning {
	enum mmc_bus_mode mode;
	qe_uint widths;
	qe_uint tuning;
};

static const struct mode_width_tuning sd_modes_by_pref[] = {
	{
		.mode = UHS_SDR104,
		.widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
		.tuning = MMC_CMD_SEND_TUNING_BLOCK
	},
	{
		.mode = UHS_SDR50,
		.widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
	},
	{
		.mode = UHS_DDR50,
		.widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
	},
	{
		.mode = UHS_SDR25,
		.widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
	},
	{
		.mode = SD_HS,
		.widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
	},
	{
		.mode = UHS_SDR12,
		.widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
	},
	{
		.mode = SD_LEGACY,
		.widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
	}
};

#define for_each_sd_mode_by_pref(caps, mwt) \
	for (mwt = sd_modes_by_pref;\
	     mwt < sd_modes_by_pref + qe_array_size(sd_modes_by_pref);\
	     mwt++) \
		if (caps & MMC_CAP(mwt->mode))

static const struct ext_csd_bus_width {
	qe_uint cap;
	qe_bool is_ddr;
	qe_uint ext_csd_bits;
} ext_csd_bus_width[] = {
	{MMC_MODE_8BIT, qe_true, MMC_EXT_CSD_DDR_BUS_WIDTH_8},
	{MMC_MODE_4BIT, qe_true, MMC_EXT_CSD_DDR_BUS_WIDTH_4},
	{MMC_MODE_8BIT, qe_false, MMC_EXT_CSD_BUS_WIDTH_8},
	{MMC_MODE_4BIT, qe_false, MMC_EXT_CSD_BUS_WIDTH_4},
	{MMC_MODE_1BIT, qe_false, MMC_EXT_CSD_BUS_WIDTH_1},
};

static const struct mode_width_tuning mmc_modes_by_pref[] = {
	{
		.mode = MMC_HS_400_ES,
		.widths = MMC_MODE_8BIT,
	},
	{
		.mode = MMC_HS_400,
		.widths = MMC_MODE_8BIT,
		.tuning = MMC_CMD_SEND_TUNING_BLOCK_HS200
	},
	{
		.mode = MMC_HS_200,
		.widths = MMC_MODE_8BIT | MMC_MODE_4BIT,
		.tuning = MMC_CMD_SEND_TUNING_BLOCK_HS200
	},
	{
		.mode = MMC_DDR_52,
		.widths = MMC_MODE_8BIT | MMC_MODE_4BIT,
	},
	{
		.mode = MMC_HS_52,
		.widths = MMC_MODE_8BIT | MMC_MODE_4BIT | MMC_MODE_1BIT,
	},
	{
		.mode = MMC_HS,
		.widths = MMC_MODE_8BIT | MMC_MODE_4BIT | MMC_MODE_1BIT,
	},
	{
		.mode = MMC_LEGACY,
		.widths = MMC_MODE_8BIT | MMC_MODE_4BIT | MMC_MODE_1BIT,
	}
};

#define for_each_mmc_mode_by_pref(caps, mwt) \
	for (mwt = mmc_modes_by_pref;\
	    mwt < mmc_modes_by_pref + qe_array_size(mmc_modes_by_pref);\
	    mwt++) \
		if (caps & MMC_CAP(mwt->mode))

#define for_each_supported_width(caps, ddr, ecbv) \
	for (ecbv = ext_csd_bus_width;\
	    ecbv < ext_csd_bus_width + qe_array_size(ext_csd_bus_width);\
	    ecbv++) \
		if ((ddr == ecbv->is_ddr) && (caps & ecbv->cap))

static inline int bus_width(qe_uint cap)
{
	if (cap == MMC_MODE_8BIT)
		return 8;
	if (cap == MMC_MODE_4BIT)
		return 4;
	if (cap == MMC_MODE_1BIT)
		return 1;
	qe_warning("invalid bus witdh capability 0x%x\n", cap);
	return 0;
}

static qe_ret sd_select_bus_width(qe_mmc *mmc, int w)
{
	qe_ret ret;
	qe_mmc_cmd cmd;

	if ((w != 4) && (w != 1))
		return qe_err_param;

	cmd.cmdidx = MMC_CMD_APP_CMD;
	cmd.resp_type = MMC_RSP_R1;
	cmd.cmdarg = mmc->rca << 16;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
	if (ret != qe_ok)
		return ret;

	cmd.cmdidx = SD_CMD_APP_SET_BUS_WIDTH;
	cmd.resp_type = MMC_RSP_R1;
	if (w == 4)
		cmd.cmdarg = 2;
	else if (w == 1)
		cmd.cmdarg = 0;
	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);

	return ret;
}

static qe_ret sd_set_card_speed(qe_mmc *mmc, enum mmc_bus_mode mode)
{
	qe_ret ret;

	qe_uint qe_aligned(32) switch_status[16];
	int speed;

	/* SD version 1.00 and 1.01 does not support CMD 6 */
	if (mmc->version == SD_VERSION_1_0)
		return 0;

	switch (mode) {
	case SD_LEGACY:
		speed = MMC_UHS_SDR12_BUS_SPEED;
		break;
	case SD_HS:
		speed = MMC_HIGH_SPEED_BUS_SPEED;
		break;
	case UHS_SDR12:
		speed = MMC_UHS_SDR12_BUS_SPEED;
		break;
	case UHS_SDR25:
		speed = MMC_UHS_SDR25_BUS_SPEED;
		break;
	case UHS_SDR50:
		speed = MMC_UHS_SDR50_BUS_SPEED;
		break;
	case UHS_DDR50:
		speed = MMC_UHS_DDR50_BUS_SPEED;
		break;
	case UHS_SDR104:
		speed = MMC_UHS_SDR104_BUS_SPEED;
		break;
	default:
		return qe_err_param;
	}

	ret = sd_switch(mmc, SD_SWITCH_SWITCH, 0, speed, (qe_u8 *)switch_status);
	if (ret != qe_ok)
		return ret;

	if (((qe_swab32(switch_status[4]) >> 24) & 0xF) != speed)
		return qe_err_notsupport;

	return qe_ok;
}

static qe_ret sd_read_ssr(qe_mmc *mmc)
{
	static const unsigned int sd_au_size[] = {
		0,		QE_SIZE_16K / 512,		QE_SIZE_32K / 512,
		QE_SIZE_64K / 512,	QE_SIZE_128K / 512,		QE_SIZE_256K / 512,
		QE_SIZE_512K / 512,	QE_SIZE_1M / 512,		QE_SIZE_2M / 512,
		QE_SIZE_4M / 512,	QE_SIZE_8M / 512,		(QE_SIZE_8M + QE_SIZE_4M) / 512,
		QE_SIZE_16M / 512,	(QE_SIZE_16M + QE_SIZE_8M) / 512,	QE_SIZE_32M / 512,
		QE_SIZE_64M / 512,
	};
	int i;
	qe_ret ret;
	qe_mmc_cmd cmd;
	qe_uint qe_aligned(32) ssr[16];
	qe_mmc_data data;
	int timeout = 3;
	unsigned int au, eo, et, es;

	cmd.cmdidx = MMC_CMD_APP_CMD;
	cmd.resp_type = MMC_RSP_R1;
	cmd.cmdarg = mmc->rca << 16;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
	if (ret != qe_ok)
		return ret;

	cmd.cmdidx = SD_CMD_APP_SD_STATUS;
	cmd.resp_type = MMC_RSP_R1;
	cmd.cmdarg = 0;

retry_ssr:
	data.dest = (char *)ssr;
	data.blocksize = 64;
	data.blocks = 1;
	data.flags = MMC_DATA_READ;

	ret = mmc_send_cmd(mmc, &cmd, &data);
	if (ret != qe_ok) {
		if (timeout--)
			goto retry_ssr;

		return ret;
	}

	for (i = 0; i < 16; i++)
		ssr[i] = qe_swab32(ssr[i]);

	au = (ssr[2] >> 12) & 0xF;
	if ((au <= 9) || (mmc->version == SD_VERSION_3)) {
		mmc->ssr.au = sd_au_size[au];
		es = (ssr[3] >> 24) & 0xFF;
		es |= (ssr[2] & 0xFF) << 8;
		et = (ssr[3] >> 18) & 0x3F;
		if (es && et) {
			eo = (ssr[3] >> 16) & 0x3;
			mmc->ssr.erase_timeout = (et * 1000) / es;
			mmc->ssr.erase_offset = eo * 1000;
		}
	} else {
		qe_error("Invalid Allocation Unit Size.");
	}

	return 0;
}

static qe_ret sd_select_mode_and_width(qe_mmc *mmc, qe_uint card_caps)
{
	qe_ret ret;
	qe_uint widths[] = {MMC_MODE_4BIT, MMC_MODE_1BIT};
	const struct mode_width_tuning *mwt;
	qe_bool uhs_en = (mmc->ocr & MMC_OCR_S18R) ? qe_true : qe_false;
	qe_uint caps;

	mmc_dump_capabilities("sd card", card_caps);
	mmc_dump_capabilities("host", mmc->host_caps);

	if (mmc_host_is_spi(mmc)) {
		mmc_set_bus_width(mmc, 1);
		mmc_select_mode(mmc, SD_LEGACY);
		mmc_set_clock(mmc, mmc->tran_speed, MMC_CLK_ENABLE);
		return qe_ok;
	}

	/* Restrict card's capabilities by what the host can do */
	caps = card_caps & mmc->host_caps;

	if (!uhs_en)
		caps &= ~MMC_UHS_CAPS;

	for_each_sd_mode_by_pref(caps, mwt) {
		qe_uint *w;

		for (w = widths; w < widths + qe_array_size(widths); w++) {
			if (*w & caps & mwt->widths) {
				qe_debug("trying mode %s width %d (at %d MHz)",
					 mmc_mode_name(mwt->mode),
					 bus_width(*w),
					 mmc_mode2freq(mmc, mwt->mode) / 1000000);

				/* configure the bus width (card + host) */
				ret = sd_select_bus_width(mmc, bus_width(*w));
				if (ret != qe_ok)
					goto error;
				mmc_set_bus_width(mmc, bus_width(*w));

				/* configure the bus mode (card) */
				ret = sd_set_card_speed(mmc, mwt->mode);
				if (ret != qe_ok)
					goto error;

				/* configure the bus mode (host) */
				mmc_select_mode(mmc, mwt->mode);
				mmc_set_clock(mmc, mmc->tran_speed,
						MMC_CLK_ENABLE);

				/* execute tuning if needed */
				if (mwt->tuning && !mmc_host_is_spi(mmc)) {
					ret = mmc_execute_tuning(mmc, mwt->tuning);
					if (ret != qe_ok) {
						qe_error("tuning error:%d", ret);
						goto error;
					}
				}

				ret = sd_read_ssr(mmc);
				if (ret != qe_ok)
					qe_warning("unable to read ssr");
				if (ret == qe_ok)
					return 0;

error:
				/* revert to a safer bus speed */
				mmc_select_mode(mmc, SD_LEGACY);
				mmc_set_clock(mmc, mmc->tran_speed,
						MMC_CLK_ENABLE);
			}
		}
	}

	qe_error("unable to select a mode");
	return qe_err_notsupport;
}

static qe_ret mmc_set_card_speed(qe_mmc *mmc, enum mmc_bus_mode mode, qe_bool hsdowngrade)
{
	qe_ret ret;
	int speed_bits;

	qe_u8 qe_aligned(32) test_csd[MMC_MAX_BLOCK_LEN];

	switch (mode) {
	case MMC_HS:
	case MMC_HS_52:
	case MMC_DDR_52:
		speed_bits = MMC_EXT_CSD_TIMING_HS;
		break;
	case MMC_HS_200:
		speed_bits = MMC_EXT_CSD_TIMING_HS200;
		break;
	case MMC_HS_400:
		speed_bits = MMC_EXT_CSD_TIMING_HS400;
		break;
	case MMC_HS_400_ES:
		speed_bits = MMC_EXT_CSD_TIMING_HS400;
		break;
	case MMC_LEGACY:
		speed_bits = MMC_EXT_CSD_TIMING_LEGACY;
		break;
	default:
		return qe_err_param;
	}

	ret = mmc_switch(mmc, MMC_EXT_CSD_CMD_SET_NORMAL, MMC_EXT_CSD_HS_TIMING, speed_bits, !hsdowngrade);
	if (ret != qe_ok)
		return ret;

	/*
	 * In case the eMMC is in HS200/HS400 mode and we are downgrading
	 * to HS mode, the card clock are still running much faster than
	 * the supported HS mode clock, so we can not reliably read out
	 * Extended CSD. Reconfigure the controller to run at HS mode.
	 */
	if (hsdowngrade) {
		mmc_select_mode(mmc, MMC_HS);
		mmc_set_clock(mmc, mmc_mode2freq(mmc, MMC_HS), qe_false);
	}

	if ((mode == MMC_HS) || (mode == MMC_HS_52)) {
		/* Now check to see that it worked */
		ret = mmc_send_ext_csd(mmc, test_csd);
		if (ret != qe_ok)
			return ret;

		/* No high-speed support */
		if (!test_csd[MMC_EXT_CSD_HS_TIMING])
			return qe_err_notsupport;
	}

	return qe_ok;
}

static inline int generic_ffs(int x)
{
	int r = 1;

	if (!x)
		return 0;
	if (!(x & 0xffff)) {
		x >>= 16;
		r += 16;
	}
	if (!(x & 0xff)) {
		x >>= 8;
		r += 8;
	}
	if (!(x & 0xf)) {
		x >>= 4;
		r += 4;
	}
	if (!(x & 3)) {
		x >>= 2;
		r += 2;
	}
	if (!(x & 1)) {
		x >>= 1;
		r += 1;
	}
	return r;
}

static int mmc_set_lowest_voltage(qe_mmc *mmc, enum mmc_bus_mode mode, qe_u32 allowed_mask)
{
	qe_u32 card_mask = 0;

	switch (mode) {
	case MMC_HS_400_ES:
	case MMC_HS_400:
	case MMC_HS_200:
		if (mmc->cardtype & (MMC_EXT_CSD_CARD_TYPE_HS200_1_8V |
				MMC_EXT_CSD_CARD_TYPE_HS400_1_8V))
			card_mask |= MMC_SIGNAL_VOLTAGE_180;
		if (mmc->cardtype & (MMC_EXT_CSD_CARD_TYPE_HS200_1_2V |
				MMC_EXT_CSD_CARD_TYPE_HS400_1_2V))
			card_mask |= MMC_SIGNAL_VOLTAGE_120;
		break;
	case MMC_DDR_52:
		if (mmc->cardtype & MMC_EXT_CSD_CARD_TYPE_DDR_1_8V)
			card_mask |= MMC_SIGNAL_VOLTAGE_330 |
				     MMC_SIGNAL_VOLTAGE_180;
		if (mmc->cardtype & MMC_EXT_CSD_CARD_TYPE_DDR_1_2V)
			card_mask |= MMC_SIGNAL_VOLTAGE_120;
		break;
	default:
		card_mask |= MMC_SIGNAL_VOLTAGE_330;
		break;
	}

	while (card_mask & allowed_mask) {
		enum mmc_voltage best_match;

		best_match = 1 << (generic_ffs(card_mask & allowed_mask) - 1);
		if (!mmc_set_signal_voltage(mmc,  best_match))
			return 0;

		allowed_mask &= ~best_match;
	}

	return qe_err_notsupport;
}

static qe_ret mmc_select_hs400(qe_mmc *mmc)
{
	qe_ret ret;

	/* Set timing to HS200 for tuning */
	ret = mmc_set_card_speed(mmc, MMC_HS_200, qe_false);
	if (ret != qe_ok)
		return ret;

	/* configure the bus mode (host) */
	mmc_select_mode(mmc, MMC_HS_200);
	mmc_set_clock(mmc, mmc->tran_speed, qe_false);

	/* execute tuning if needed */
	ret = mmc_execute_tuning(mmc, MMC_CMD_SEND_TUNING_BLOCK_HS200);
	if (ret != qe_ok) {
		qe_debug("tuning failed\n");
		return ret;
	}

	/* Set back to HS */
	mmc_set_card_speed(mmc, MMC_HS, qe_true);

	ret = mmc_switch(mmc, MMC_EXT_CSD_CMD_SET_NORMAL, MMC_EXT_CSD_BUS_WIDTH,
			 MMC_EXT_CSD_BUS_WIDTH_8 | MMC_EXT_CSD_DDR_FLAG, qe_true);
	if (ret != qe_ok)
		return ret;

	ret = mmc_set_card_speed(mmc, MMC_HS_400, qe_false);
	if (ret != qe_ok)
		return ret;

	mmc_select_mode(mmc, MMC_HS_400);
	ret = mmc_set_clock(mmc, mmc->tran_speed, qe_false);
	if (ret != qe_ok)
		return ret;

	return qe_ok;
}

static qe_ret mmc_set_enhanced_strobe(qe_mmc *mmc)
{
	return qe_err_notsupport;
}

static qe_ret mmc_select_hs400es(qe_mmc *mmc)
{
	qe_ret ret;

	ret = mmc_set_card_speed(mmc, MMC_HS, qe_true);
	if (ret != qe_ok)
		return ret;

	ret = mmc_switch(mmc, MMC_EXT_CSD_CMD_SET_NORMAL, MMC_EXT_CSD_BUS_WIDTH,
			 MMC_EXT_CSD_BUS_WIDTH_8 | MMC_EXT_CSD_DDR_FLAG |
			 MMC_EXT_CSD_BUS_WIDTH_STROBE, qe_true);
	if (ret != qe_ok) {
		qe_error("switch to bus width for hs400 failed");
		return ret;
	}
	/* TODO: driver strength */
	ret = mmc_set_card_speed(mmc, MMC_HS_400_ES, qe_false);
	if (ret != qe_ok)
		return ret;

	mmc_select_mode(mmc, MMC_HS_400_ES);
	ret = mmc_set_clock(mmc, mmc->tran_speed, qe_false);
	if (ret != qe_ok)
		return ret;

	return mmc_set_enhanced_strobe(mmc);
}

static qe_ret mmc_read_and_compare_ext_csd(qe_mmc *mmc)
{
	qe_ret ret;
	const qe_u8 *ext_csd = mmc->ext_csd;
	qe_u8 qe_aligned(32) test_csd[MMC_MAX_BLOCK_LEN];

	if (mmc->version < MMC_VERSION_4)
		return qe_ok;

	ret = mmc_send_ext_csd(mmc, test_csd);
	if (ret != qe_ok)
		return ret;

	/* Only compare read only fields */
	if (ext_csd[MMC_EXT_CSD_PARTITIONING_SUPPORT]
		== test_csd[MMC_EXT_CSD_PARTITIONING_SUPPORT] &&
	    ext_csd[MMC_EXT_CSD_HC_WP_GRP_SIZE]
		== test_csd[MMC_EXT_CSD_HC_WP_GRP_SIZE] &&
	    ext_csd[MMC_EXT_CSD_REV]
		== test_csd[MMC_EXT_CSD_REV] &&
	    ext_csd[MMC_EXT_CSD_HC_ERASE_GRP_SIZE]
		== test_csd[MMC_EXT_CSD_HC_ERASE_GRP_SIZE] &&
	    qe_memcmp(&ext_csd[MMC_EXT_CSD_SEC_CNT],
		   &test_csd[MMC_EXT_CSD_SEC_CNT], 4) == 0)
		return 0;

	return qe_err_notsupport;
}

static qe_ret mmc_select_mode_and_width(qe_mmc *mmc, qe_uint card_caps)
{
	qe_ret ret;
	const struct mode_width_tuning *mwt;
	const struct ext_csd_bus_width *ecbw;

	mmc_dump_capabilities("mmc", card_caps);
	mmc_dump_capabilities("host", mmc->host_caps);

	if (mmc_host_is_spi(mmc)) {
		mmc_set_bus_width(mmc, 1);
		mmc_select_mode(mmc, MMC_LEGACY);
		mmc_set_clock(mmc, mmc->tran_speed, MMC_CLK_ENABLE);
		return qe_ok;
	}

	/* Restrict card's capabilities by what the host can do */
	card_caps &= mmc->host_caps;

	/* Only version 4 of MMC supports wider bus widths */
	if (mmc->version < MMC_VERSION_4)
		return qe_ok;

	if (!mmc->ext_csd) {
		qe_error("No ext_csd found!\n"); /* this should enver happen */
		return qe_err_notsupport;
	}

	/*
	 * In case the eMMC is in HS200/HS400 mode, downgrade to HS mode
	 * before doing anything else, since a transition from either of
	 * the HS200/HS400 mode directly to legacy mode is not supported.
	 */
	if (mmc->selected_mode == MMC_HS_200 ||
	    mmc->selected_mode == MMC_HS_400)
		mmc_set_card_speed(mmc, MMC_HS, qe_true);
	else
		mmc_set_clock(mmc, mmc->legacy_speed, MMC_CLK_ENABLE);

	for_each_mmc_mode_by_pref(card_caps, mwt) {
		for_each_supported_width(card_caps & mwt->widths,
					 mmc_is_mode_ddr(mwt->mode), ecbw) {
			enum mmc_voltage old_voltage;
			qe_debug("trying mode %s width %d (at %d MHz)",
				 mmc_mode_name(mwt->mode),
				 bus_width(ecbw->cap),
				 mmc_mode2freq(mmc, mwt->mode) / 1000000);
			old_voltage = mmc->signal_voltage;
			ret = mmc_set_lowest_voltage(mmc, mwt->mode,
						     MMC_ALL_SIGNAL_VOLTAGE);
			if (ret != qe_ok)
				continue;

			/* configure the bus width (card + host) */
			ret = mmc_switch(mmc, MMC_EXT_CSD_CMD_SET_NORMAL,
				    MMC_EXT_CSD_BUS_WIDTH,
				    ecbw->ext_csd_bits & ~MMC_EXT_CSD_DDR_FLAG, qe_true);
			if (ret != qe_ok)
				goto error;
			mmc_set_bus_width(mmc, bus_width(ecbw->cap));

			if (mwt->mode == MMC_HS_400) {
				ret = mmc_select_hs400(mmc);
				if (ret != qe_ok) {
					qe_error("select HS400 failed %d", ret);
					goto error;
				}
			} else if (mwt->mode == MMC_HS_400_ES) {
				ret = mmc_select_hs400es(mmc);
				if (ret != qe_ok) {
					qe_error("Select HS400ES failed %d", ret);
					goto error;
				}
			} else {
				/* configure the bus speed (card) */
				ret = mmc_set_card_speed(mmc, mwt->mode, qe_false);
				if (ret != qe_ok)
					goto error;

				/*
				 * configure the bus width AND the ddr mode
				 * (card). The host side will be taken care
				 * of in the next step
				 */
				if (ecbw->ext_csd_bits & MMC_EXT_CSD_DDR_FLAG) {
					ret = mmc_switch(mmc,
							 MMC_EXT_CSD_CMD_SET_NORMAL,
							 MMC_EXT_CSD_BUS_WIDTH,
							 ecbw->ext_csd_bits,
							 qe_true);
					if (ret != qe_ok)
						goto error;
				}

				/* configure the bus mode (host) */
				mmc_select_mode(mmc, mwt->mode);
				mmc_set_clock(mmc, mmc->tran_speed,
					      MMC_CLK_ENABLE);

				/* execute tuning if needed */
				if (mwt->tuning) {
					ret = mmc_execute_tuning(mmc,
								 mwt->tuning);
					if (ret != qe_ok) {
						qe_debug("tuning failed");
						goto error;
					}
				}
			}

			/* do a transfer to check the configuration */
			ret = mmc_read_and_compare_ext_csd(mmc);
			if (ret == qe_ok)
				return ret;
error:
			mmc_set_signal_voltage(mmc, old_voltage);
			/* if an error occured, revert to a safer bus mode */
			mmc_switch(mmc, MMC_EXT_CSD_CMD_SET_NORMAL,
				   MMC_EXT_CSD_BUS_WIDTH, MMC_EXT_CSD_BUS_WIDTH_1, qe_true);
			mmc_select_mode(mmc, MMC_LEGACY);
			mmc_set_bus_width(mmc, 1);
		}
	}

	qe_error("unable to select a mode\n");

	return qe_err_notsupport;
}

static qe_ret mmc_get_capabilities(qe_mmc *mmc)
{
	qe_u8 *ext_csd = mmc->ext_csd;
	char cardtype;

	mmc->card_caps = MMC_MODE_1BIT | MMC_CAP(MMC_LEGACY);

	if (mmc_host_is_spi(mmc))
		return qe_ok;

	/* Only version 4 supports high-speed */
	if (mmc->version < MMC_VERSION_4)
		return qe_ok;

	if (!ext_csd) {
		qe_error("no ext_csd found!"); /* this should enver happen */
		return qe_err_notsupport;
	}

	mmc->card_caps |= MMC_MODE_4BIT | MMC_MODE_8BIT;

	cardtype = ext_csd[MMC_EXT_CSD_CARD_TYPE];
	mmc->cardtype = cardtype;

	if (cardtype & (MMC_EXT_CSD_CARD_TYPE_HS200_1_2V |
			MMC_EXT_CSD_CARD_TYPE_HS200_1_8V)) {
		mmc->card_caps |= MMC_MODE_HS200;
	}

	if (cardtype & (MMC_EXT_CSD_CARD_TYPE_HS400_1_2V |
			MMC_EXT_CSD_CARD_TYPE_HS400_1_8V)) {
		mmc->card_caps |= MMC_MODE_HS400;
	}

	if (cardtype & MMC_EXT_CSD_CARD_TYPE_52) {
		if (cardtype & MMC_EXT_CSD_CARD_TYPE_DDR_52)
			mmc->card_caps |= MMC_MODE_DDR_52MHz;
		mmc->card_caps |= MMC_MODE_HS_52MHz;
	}
	if (cardtype & MMC_EXT_CSD_CARD_TYPE_26)
		mmc->card_caps |= MMC_MODE_HS;

	if (ext_csd[MMC_EXT_CSD_STROBE_SUPPORT] &&
	    (mmc->card_caps & MMC_MODE_HS400)) {
		mmc->card_caps |= MMC_MODE_HS400_ES;
	}

	return qe_ok;
}

static qe_ret mmc_startup(qe_mmc *mmc)
{
    int i;
	qe_ret ret; 
	qe_uint mult, freq;
	qe_u64 cmult, csize;
	qe_mmc_cmd cmd;

	if (mmc_host_is_spi(mmc)) { /* enable CRC check for spi */
		cmd.cmdidx = MMC_CMD_SPI_CRC_ON_OFF;
		cmd.resp_type = MMC_RSP_R1;
		cmd.cmdarg = 1;
		ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
		if (ret != qe_ok)
			return ret;
	}

	/* Put the Card in Identify Mode */
	cmd.cmdidx = mmc_host_is_spi(mmc) ? MMC_CMD_SEND_CID :
		MMC_CMD_ALL_SEND_CID; /* cmd not supported in spi */
	cmd.resp_type = MMC_RSP_R2;
	cmd.cmdarg = 0;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
	if (ret != qe_ok)
		return ret;

	qe_memcpy(mmc->cid, cmd.response, 16);
    qe_debug("cid %x %x %x %x", mmc->cid[0], mmc->cid[1], mmc->cid[2], mmc->cid[3]);

	/*
	 * For MMC cards, set the Relative Address.
	 * For SD cards, get the Relatvie Address.
	 * This also puts the cards into Standby State
	 */
	if (!mmc_host_is_spi(mmc)) { /* cmd not supported in spi */
		cmd.cmdidx = SD_CMD_SEND_RELATIVE_ADDR;
		cmd.cmdarg = mmc->rca << 16;
		cmd.resp_type = MMC_RSP_R6;

		ret = mmc_send_cmd(mmc, &cmd, QE_NULL);

		if (ret != qe_ok)
			return ret;

		if (MMC_IS_SD(mmc))
			mmc->rca = (cmd.response[0] >> 16) & 0xffff;
	}

	/* Get the Card-Specific Data */
	cmd.cmdidx = MMC_CMD_SEND_CSD;
	cmd.resp_type = MMC_RSP_R2;
	cmd.cmdarg = mmc->rca << 16;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);

	if (ret != qe_ok)
		return ret;

	mmc->csd[0] = cmd.response[0];
	mmc->csd[1] = cmd.response[1];
	mmc->csd[2] = cmd.response[2];
	mmc->csd[3] = cmd.response[3];
    qe_debug("csd %x %x %x %x", mmc->csd[0], mmc->csd[1], mmc->csd[2], mmc->csd[3]);

	if (mmc->version == MMC_VERSION_UNKNOWN) {
		int version = (cmd.response[0] >> 26) & 0xf;

		switch (version) {
		case 0:
			mmc->version = MMC_VERSION_1_2;
			break;
		case 1:
			mmc->version = MMC_VERSION_1_4;
			break;
		case 2:
			mmc->version = MMC_VERSION_2_2;
			break;
		case 3:
			mmc->version = MMC_VERSION_3;
			break;
		case 4:
			mmc->version = MMC_VERSION_4;
			break;
		default:
			mmc->version = MMC_VERSION_1_2;
			break;
		}
	}

    qe_debug("version:%x", mmc->version);

	/* divide frequency by 10, since the mults are 10x bigger */
	freq = fbase[(cmd.response[0] & 0x7)];
	mult = multipliers[((cmd.response[0] >> 3) & 0xf)];

	mmc->legacy_speed = freq * mult;
	mmc_select_mode(mmc, MMC_LEGACY);

	mmc->dsr_imp = ((cmd.response[1] >> 12) & 0x1);
	mmc->read_bl_len = 1 << ((cmd.response[1] >> 16) & 0xf);

	if (MMC_IS_SD(mmc))
		mmc->write_bl_len = mmc->read_bl_len;
	else
		mmc->write_bl_len = 1 << ((cmd.response[3] >> 22) & 0xf);

	qe_debug("high_capacity:%d", mmc->high_capacity);
	if (mmc->high_capacity) {
		csize = (mmc->csd[1] & 0x3f) << 16
			| (mmc->csd[2] & 0xffff0000) >> 16;
		cmult = 8;
	} else {
		csize = (mmc->csd[1] & 0x3ff) << 2
			| (mmc->csd[2] & 0xc0000000) >> 30;
		cmult = (mmc->csd[2] & 0x00038000) >> 15;
	}

	mmc->capacity_user = (csize + 1) << (cmult + 2);
	mmc->capacity_user *= mmc->read_bl_len;
	mmc->capacity_boot = 0;
	mmc->capacity_rpmb = 0;
	for (i = 0; i < 4; i++)
		mmc->capacity_gp[i] = 0;

	if (mmc->read_bl_len > MMC_MAX_BLOCK_LEN)
		mmc->read_bl_len = MMC_MAX_BLOCK_LEN;

	if (mmc->write_bl_len > MMC_MAX_BLOCK_LEN)
		mmc->write_bl_len = MMC_MAX_BLOCK_LEN;

    qe_debug("capacity    : %llu", mmc->capacity_user);
    qe_debug("read block  : %u", mmc->read_bl_len);
    qe_debug("write block : %u", mmc->write_bl_len);

	if ((mmc->dsr_imp) && (0xffffffff != mmc->dsr)) {
		cmd.cmdidx = MMC_CMD_SET_DSR;
		cmd.cmdarg = (mmc->dsr & 0xffff) << 16;
		cmd.resp_type = MMC_RSP_NONE;
		ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
        if (ret != qe_ok)
			qe_warning("set dsr error:%d");
	}

	/* Select the card, and put it into Transfer Mode */
	if (!mmc_host_is_spi(mmc)) { /* cmd not supported in spi */
		cmd.cmdidx = MMC_CMD_SELECT_CARD;
		cmd.resp_type = MMC_RSP_R1;
		cmd.cmdarg = mmc->rca << 16;
		ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
		if (ret != qe_ok)
			return ret;
	}
    qe_debug("selected card");

	/*
	 * For SD, its erase group is always one sector
	 */
	mmc->erase_grp_size = 1;
	mmc->part_config = MMC_PART_NOAVAILABLE;

	ret = mmc_startup_v4(mmc);
	if (ret != qe_ok)
		return ret;

	ret = mmc_set_capacity(mmc, 0);
	if (ret != qe_ok)
		return ret;
    qe_debug("set capacity %llx", mmc->capacity);

	if (MMC_IS_SD(mmc)) {
		ret = sd_get_capabilities(mmc);
		if (ret != qe_ok)
			return ret;
		ret = sd_select_mode_and_width(mmc, mmc->card_caps);
	} else {
		ret = mmc_get_capabilities(mmc);
		if (ret != qe_ok)
			return ret;
		mmc_select_mode_and_width(mmc, mmc->card_caps);
	}

	if (ret != qe_ok)
		return ret;

	mmc->best_mode = mmc->selected_mode;

	/* Fix the block length for DDR mode */
	if (mmc->ddr_mode) {
		mmc->read_bl_len = MMC_MAX_BLOCK_LEN;
		mmc->write_bl_len = MMC_MAX_BLOCK_LEN;
	}

    qe_debug("vendor man:%06x snr:%04x%04x", 
        mmc->cid[0] >> 24, (mmc->cid[2] & 0xffff),
        (mmc->cid[3] >> 16) & 0xffff);

	qe_debug("%c%c%c%c%c%c", mmc->cid[0] & 0xff,
		(mmc->cid[1] >> 24), (mmc->cid[1] >> 16) & 0xff,
		(mmc->cid[1] >> 8) & 0xff, mmc->cid[1] & 0xff,
		(mmc->cid[2] >> 24) & 0xff);

	qe_debug("%d.%d", (mmc->cid[2] >> 20) & 0xf, (mmc->cid[2] >> 16) & 0xf);

	return qe_ok;
}

static qe_ret mmc_complete_init(qe_mmc *mmc)
{
	qe_ret ret = qe_ok;

	mmc->init_in_progress = 0;
	if (mmc->op_cond_pending)
		ret = mmc_complete_op_cond(mmc);
    qe_info("mmc_complete_op_cond ret:%d", ret);
	if (ret == qe_ok)
		ret = mmc_startup(mmc);
	if (ret != qe_ok)
		mmc->has_init = 0;
	else
		mmc->has_init = 1;
	return ret;
}

static qe_ret mmc_init(qe_mmc *mmc)
{
	qe_ret ret;

    qe_debug("%s init in", mmc->dev.name);

    if (mmc->has_init) {
        qe_info("%s has initialized", mmc->dev.name);
        return qe_ok;
    }

    if (!mmc->init_in_progress)
        ret = mmc_start_init(mmc);
    
    if (ret == qe_ok)
        ret = mmc_complete_init(mmc);
    
    if (ret != qe_ok) {
        qe_error("%s init error:%d", mmc->dev.name, ret);
    }

    return ret;
}

static qe_ret mmc_set_blocklen(qe_mmc *mmc, int len)
{
    qe_ret ret;
	qe_mmc_cmd cmd;

	if (mmc->ddr_mode)
		return qe_ok;

	cmd.cmdidx = MMC_CMD_SET_BLOCKLEN;
	cmd.resp_type = MMC_RSP_R1;
	cmd.cmdarg = len;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);

	return ret;
}

void qe_mmc_list_devices(void)
{
    qe_mmc *p;

    qe_list_foreach_entry(p, &mmc_list, list) {
        qe_printf("%s\r\n", p->dev.name);
    }
}

qe_ret qe_mmc_init_device(qe_mmc *mmc, qe_bool force_init)
{
    if (mmc_getcd(mmc))
        force_init = qe_true;

    if (force_init)
        mmc->has_init = qe_false;
    
    return mmc_init(mmc);
}

qe_ret qe_mmc_register(qe_mmc *mmc, qe_const_str name, const qe_mmc_ops *ops, void *priv)
{
    qe_dev *dev = &mmc->dev;
    qe_list_append(&mmc->list, &mmc_list);
    mmc->ops = ops;
    mmc->priv = priv;
    return qe_dev_register(dev, name, 0x0);
}

qe_size qe_mmc_bread(qe_mmc *mmc, qe_size start, qe_size blkcnt, qe_ptr dst)
{
    qe_ret ret;
    qe_size cur;
    qe_size blocks_todo;

    if (blkcnt == 0)
        return 0;

    if ((start + blkcnt) > mmc->lba) {
        qe_error("%s block number %d exceeds max:%d", 
            mmc->dev.name, start + blkcnt, mmc->lba);
        return -(qe_err_range);
    }

    ret = mmc_set_blocklen(mmc, mmc->read_bl_len);
    if (ret != qe_ok) {
        qe_error("%s set blocklen error:%d",
            mmc->dev.name, ret);
        return -ret;
    }

    blocks_todo = blkcnt;
    do {
		cur = (blocks_todo > mmc->cfg->b_max) ?
			mmc->cfg->b_max : blocks_todo;
		if (mmc_read_blocks(mmc, start, cur, dst) != cur) {
			qe_error("%s failed to read blocks", mmc->dev.name);
			return -qe_err_common;
		}
		blocks_todo -= cur;
		start += cur;
		dst += cur * mmc->read_bl_len;
    } while (blocks_todo > 0);

    return blkcnt;
}

qe_size qe_mmc_bwrite(qe_mmc *mmc, qe_size start, qe_size blkcnt, qe_const_ptr src)
{
	qe_ret ret;
    qe_size cur;
    qe_size blocks_todo = blkcnt;

    ret = mmc_set_blocklen(mmc, mmc->write_bl_len);
    if (ret != qe_ok) {
        qe_error("%s set blocklen error:%d",
            mmc->dev.name, ret);
        return -ret;
    }

	do {
		cur = (blocks_todo > mmc->cfg->b_max) ?
			mmc->cfg->b_max : blocks_todo;
		if (mmc_write_blocks(mmc, start, cur, src) != cur)
			return 0;
		blocks_todo -= cur;
		start += cur;
		src += cur * mmc->write_bl_len;
	} while (blocks_todo > 0);

	return blkcnt;
}

static qe_ret mmc_erase_blocks(qe_mmc *mmc, qe_size start, qe_size blkcnt)
{
    qe_ret ret;
	qe_mmc_cmd cmd;
	qe_size end;
	int start_cmd, end_cmd;

	if (mmc->high_capacity) {
		end = start + blkcnt - 1;
	} else {
		end = (start + blkcnt - 1) * mmc->write_bl_len;
		start *= mmc->write_bl_len;
	}

	if (MMC_IS_SD(mmc)) {
		start_cmd = SD_CMD_ERASE_WR_BLK_START;
		end_cmd = SD_CMD_ERASE_WR_BLK_END;
	} else {
		start_cmd = MMC_CMD_ERASE_GROUP_START;
		end_cmd = MMC_CMD_ERASE_GROUP_END;
	}

	cmd.cmdidx = start_cmd;
	cmd.cmdarg = start;
	cmd.resp_type = MMC_RSP_R1;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
	if (ret != qe_ok)
		goto err_out;

	cmd.cmdidx = end_cmd;
	cmd.cmdarg = end;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
	if (ret != qe_ok)
		goto err_out;

	cmd.cmdidx = MMC_CMD_ERASE;
	cmd.cmdarg = MMC_ERASE_ARG;
	cmd.resp_type = MMC_RSP_R1b;

	ret = mmc_send_cmd(mmc, &cmd, QE_NULL);
	if (ret != qe_ok)
		goto err_out;

	return qe_ok;

err_out:
	qe_error("mmc erase failed\n");
	return ret;
}

qe_size qe_mmc_berase(qe_mmc *mmc, qe_size start, qe_size blkcnt)
{
    qe_ret ret;
    int timeout_ms = 1000;
    qe_size blk, blk_r;

	while (blk < blkcnt) {
		if (MMC_IS_SD(mmc) && mmc->ssr.au) {
			blk_r = ((blkcnt - blk) > mmc->ssr.au) ?
				mmc->ssr.au : (blkcnt - blk);
		} else {
			blk_r = ((blkcnt - blk) > mmc->erase_grp_size) ?
				mmc->erase_grp_size : (blkcnt - blk);
		}
		ret = mmc_erase_blocks(mmc, start + blk, blk_r);
		if (ret != qe_ok)
			break;

		blk += blk_r;

		/* Waiting for the ready status */
		if (mmc_poll_for_busy(mmc, timeout_ms))
			return 0;
	}

    return blk;
}
